import fs from 'fs'
import path from 'path'
import { EventsHandler, IEventHandler, CommandBus } from '@nestjs/cqrs'
import { AvatarCreateEvent } from './create-avatar.event'
import { ConfigService } from '@nestjs/config'
import { ResizeImageCommand } from '@/image/commands/resize-image.command'
@EventsHandler(AvatarCreateEvent)
export class AvatarCreateEventHandler implements IEventHandler<AvatarCreateEvent>{
  constructor(private readonly commandBus: CommandBus, private readonly configService: ConfigService) { }

  handle(event: AvatarCreateEvent) {
    // 准备数据
    const { filename } = event.params
    // 头像路径
    const avatarPath = path.join(
      this.configService.get<string>('UPLOAD.avatar'),
      filename
    )
    // 文件不存在
    if (!fs.existsSync(avatarPath)) return
    //  调整大小后的存储位置
    const avatarResizePath = this.configService.get('UPLOAD.avatarResize')
    // 调整大小命令
    this.commandBus.execute(new ResizeImageCommand({
      filename,
      filepath: avatarPath,
      dest: avatarResizePath,
      sizes: [
        {
          suffix: 'large',
          width: 256,
          height: 256,
          fit: 'cover'
        },
        {
          suffix: 'medium',
          width: 128,
          height: 128,
          fit: 'cover'
        },
        {
          suffix: 'small',
          width: 64,
          height: 64,
          fit: 'cover'
        }
      ]
    }))
  }
}